//
//  StwxDetailViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/23.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "StwxDetailViewModel.h"

#import "StwxCommentItemViewModel.h"

#import "TransmitsListData.h"

@interface StwxDetailViewModel()

@property (nonatomic, readwrite, strong) StwxDetailItemViewModel* detailItemVM;

@property (nonatomic, strong) ArticleListData* articleListData;
@property (nonatomic, strong) ArticleInfoData* articleInfoData;

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;
@property (nonatomic, readwrite, strong) RACCommand* requestCollectCmd;
@property (nonatomic, readwrite, strong) RACCommand* requestGoodCmd;
@property (nonatomic, readwrite, strong) RACCommand* checkDownloadCmd;
@property (nonatomic, readwrite, strong) RACCommand* downloadCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;

@end

@implementation StwxDetailViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.isHaveDownload = NO;
    self.isHaveDetailCtrl = YES;
    self.isCollect = NO;
    
    self.tabIndex = 0;
    
    self.lastPage = 999;
    
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = NO;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    //    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(ArticleItemViewModel * itemViewModel) {
    //        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
    //                [subscriber sendNext:itemViewModel];
    //                [subscriber sendCompleted];
    //            });
    //            return nil;
    //        }];
    //    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.requestDataCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        return [self _requestDetailSignal:self.articleID];
    }];
    
    self.requestCollectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        @weakify(self);
        return [[self _checkUserSignal] then:^RACSignal *
        {
            @strongify(self);
            
            return [self _requestCollectSignal];
        }];
    }];
    self.requestGoodCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
       
        @weakify(self);
        return [[self _checkUserSignal] then:^RACSignal *
        {
            @strongify(self);
            
            return [self _requestGoodSignal];
        }];
    }];
    
    self.downloadCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self)
        
        return [self _requestDownloadSignal];
    }];
    
    self.checkDownloadCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self)
         
        @weakify(self)
        return [self _requestCheckDownloadSignal];
    }];
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    [[um rac_signalForSelector:@selector(userDataRefresh)] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self.requestDataCmd execute:nil];
    }];
}

- (void)initStwxDetail:(StwxDetailItemViewModel*)ivm
{
    @weakify(self);
    
    self.detailItemVM = ivm;
    
    ArticleInfoData* aInfoData = _detailItemVM.data;
    
    self.isCollect = aInfoData.isCollect;
    self.isPraise = aInfoData.isPraise;
    self.downloadNeedCoin = [aInfoData.money integerValue];
    self.isHaveDownload = [aInfoData.type isEqualToString:@"2"];/*aInfoData.download!=nil && [aInfoData.download isNotBlank];*/
    
    RAC(self, tabIndex) = RACObserve(self, detailItemVM.tabIndex);
    
    [RACObserve(self, tabIndex) subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self.requestRemoteDataCommand execute:@0];
     }];
    
    _detailItemVM.isHaveCtrl = self.isHaveDetailCtrl;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = self.isHaveDetailCtrl /*_detailItemVM.isHaveCtrl*/;
}

- (RACSignal*)_checkUserSignal
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
    {
        @strongify(self);
        
        if (um.userData!=nil && [um.userData.userID isNotBlank])
        {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
        }
        else
        {
            //错误处理
            
            NSString* strError = @"请登录后再操作！";
            [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
            [subscriber sendCompleted];
        }
        
        return nil;
    }];
}

- (RACSignal *)_requestDetailSignal:(NSString*)articleID
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    NSString* userID = [um isLogined] ? um.userData.userID : @"";

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_articledetail params:interface_param_articledetail(articleID, userID)] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     ArticleInfoData* data = [ArticleInfoData modelWithJSON:x];
                     
                     self.isHaveDetailCtrl = [data.cateID isEqualToString:@"59"];
                     
                     StwxDetailItemViewModel* ivm = [[StwxDetailItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                     
                     [self initStwxDetail:ivm];
                     
                     [subscriber sendNext:ivm];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"请求详情失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)_requestCollectSignal
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        ArticleInfoData* infoData = self.detailItemVM.data;
        
        NSString* userID = um.userData.userID;
        NSString* type = @"1";
        NSString* articleID = infoData.articleID;
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:url_interface_articlecollect params:interface_param_articlecollect(userID, type, articleID)] subscribeNext:^(id x)
         {
             @strongify(self);
             
             NSString* strMsg = x[SUCommandSysMessageKey];
             
             BOOL isCancel = [strMsg containsString:@"取消"];
             self.isCollect = !isCancel;
             
             [subscriber sendNext:strMsg];
             [subscriber sendCompleted];
             
         } error:^(NSError *error)
         {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"收藏操作失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)_requestGoodSignal
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        ArticleInfoData* infoData = self.detailItemVM.data;
        
        NSString* userID = um.userData.userID;
        NSString* type = @"2";
        NSString* articleID = infoData.articleID;
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:url_interface_articlecollect params:interface_param_articlecollect(userID, type, articleID)] subscribeNext:^(id x)
         {
             @strongify(self);
             
             NSString* strMsg = x[SUCommandSysMessageKey];
             
             BOOL isCancel = [strMsg containsString:@"取消"];
             self.isPraise = !isCancel;
             
             [subscriber sendNext:strMsg];
             [subscriber sendCompleted];
             
         } error:^(NSError *error)
         {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"点赞操作失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)_requestCheckDownloadSignal
{
    @weakify(self)
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self)
                
                @weakify(self)
                [[AFNetWorkUtils racPOSTWthURL:url_interface_downloadfee params:interface_param_downloadfee(um.userData.userID, self.articleID)] subscribeNext:^(id x)
                {
                    [subscriber sendNext:@YES];
                    [subscriber sendCompleted];
                } error:^(NSError *error)
                {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }];
                
                return nil;
            }];
}

- (RACSignal*)_requestDownloadSignal
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self)
                
                ArticleInfoData* curData = self.detailItemVM.data;
                
                UserManagerV2* uMgr = [UserManagerV2 sharedUserManagerV2];

                NSArray* strSeparates = [curData.download componentsSeparatedByString:@"/"];
                NSString* fileName = strSeparates.lastObject;

                NSString* strPath = @"";
                strPath = [strPath stringByAppendingString:uMgr.userData.userID];
                strPath = [strPath stringByAppendingString:@"/"];
                strPath = [strPath stringByAppendingString:fileName];

                [[AFNetWorkUtils racDOWNLOADWthURL:curData.download savePath:strPath] subscribeNext:^(id x)
                 {
                     [subscriber sendNext:x];
                 }
                                                                                                  completed:^
                 {
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    if (!_isHaveDetailCtrl)
    {
        self.dataSource = @[];
        self.lastPage = self.page;
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        ArticleInfoData* infoData = self.detailItemVM.data;
        
        NSString* type = self.tabIndex==0 ? @"3" : @"2";
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:url_interface_getarticleparameter params:interface_param_getarticleparameter(infoData.articleID, type, @(page + 1), @(List_PageSize))] subscribeNext:^(id x)
         {
             @strongify(self);
             
             TransmitsListData* listData = [TransmitsListData modelWithJSON:x];
             
             @weakify(self);
             NSArray *viewModels = [listData.datas.rac_sequence map:^StwxCommentItemViewModel *(TransmitListData* tListData)
                                    {
                                        @strongify(self);
                                        
                                        //计算当前cellheight
                                        StwxCommentItemViewModel *itemViewModel = [[StwxCommentItemViewModel alloc] initWithData:tListData cellHeight:self.cellHeight];
                                        
                                        return itemViewModel;
                                    }].array;
             
             if (viewModels == nil) viewModels = @[];
             
             if (self.shouldPullUpToLoadMore)
             {
                 if (0 == page)
                 {
                     self.dataSource = viewModels;
                 }
                 else
                 {
                     if (self.dataSource == nil)
                     {
                         self.dataSource = viewModels;
                     }
                     else
                     {
                         self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                     }
                 }
             }
             else
             {
                 self.dataSource = viewModels;
             }
             
             [subscriber sendNext:nil];
             [subscriber sendCompleted];
             
         } error:^(NSError *error)
         {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"加载列表数据失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

@end
